package com.jarvis.app.car.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.jarvis.app.car.AddStaffActivity;
import com.jarvis.app.car.EditStaffActivity;
import com.jarvis.app.car.LoginActivity;
import com.jarvis.app.car.R;
import com.jarvis.app.car.RegisterActivity;
import com.jarvis.app.car.adapter.StaffItemAdapter;
import com.jarvis.app.car.common.MessageResult;
import com.jarvis.app.car.constant.AppConstant;
import com.jarvis.app.car.model.Car;
import com.jarvis.app.car.model.User;
import com.jarvis.app.car.util.ServiceManager;
import com.jarvis.app.car.util.ThreadPoolManager;

import org.json.JSONObject;
import org.json.JSONStringer;
import org.json.JSONTokener;

import java.util.List;
import java.util.stream.Collectors;

/**
 * A simple {@link Fragment} subclass.
 * <p>
 * create an instance of this fragment.
 */
public class StaffFragment extends Fragment {

    private View view;
    private RecyclerView staffRecyclerView;

    private StaffItemAdapter staffItemAdapter;

    private ImageView iv_addStaffImageView;

    private final Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message message) {
            MessageResult<List<User>> messageResult = (MessageResult<List<User>>) message.obj;
            if (!messageResult.isJudgeSuccess()) {
                Toast.makeText(getActivity(), "用户名/密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            } else {
                List<User> result = messageResult.getResult();
                if (result != null && !result.isEmpty()) {
                    result = result.stream().filter(x -> x.getBolSuper() == 0).collect(Collectors.toList());
                }
                staffItemAdapter.setUserList(result);
            }
        }
    };


    private final Handler deleteHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(@NonNull Message message) {
            MessageResult<List<User>> messageResult = (MessageResult<List<User>>) message.obj;
            if (!messageResult.isJudgeSuccess()) {
                Toast.makeText(getActivity(), messageResult.getMsg(), Toast.LENGTH_SHORT).show();
                return;
            } else {
                loadUserData();
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_staff, container, false);
        staffRecyclerView = view.findViewById(R.id.staffRecyclerView);
        iv_addStaffImageView = view.findViewById(R.id.iv_addStaffImageView);

        iv_addStaffImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddStaffActivity.class);
                startActivityForResult(intent, Integer.MIN_VALUE);
            }
        });


        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        staffItemAdapter = new StaffItemAdapter(getActivity());
        staffRecyclerView.setAdapter(staffItemAdapter);


        staffItemAdapter.setItemViewOnClickListener(new StaffItemAdapter.ItemViewOnClickListener() {
            @Override
            public void deleteOnLongClick(User user, int position) {
                new AlertDialog.Builder(getContext())
                        .setTitle("温馨提示！")
                        .setMessage("确定要删除吗？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ThreadPoolManager.threadPoolExecutor.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        MessageResult<Void> listMessageResult = ServiceManager.userService.delete(user.getId());

                                        Message msg = Message.obtain();
                                        msg.obj = listMessageResult;
                                        deleteHandler.sendMessage(msg);

                                    }
                                });
                            }
                        })
                        .show();


            }

            @Override
            public void editOnClick(User user, int position) {
                Intent intent = new Intent(getActivity(), EditStaffActivity.class);
                intent.putExtra("userId", user.getId());
                startActivityForResult(intent, Integer.MIN_VALUE);


            }
        });
        loadUserData();

        super.onActivityCreated(savedInstanceState);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Integer.MIN_VALUE) {
            loadUserData();
        }
    }


    public void loadUserData() {
        ThreadPoolManager.threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                MessageResult<List<User>> listMessageResult = ServiceManager.userService.listAll();

                Message msg = Message.obtain();
                msg.obj = listMessageResult;
                handler.sendMessage(msg);

            }
        });
    }

}